<?php

namespace App\AgentAdmin\Controllers;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Models\Agent;
use App\Models\AgentLoginLog;
use Dcat\Admin\Admin;
use Illuminate\Foundation\Auth\ThrottlesLogins;

use Dcat\Admin\Http\Controllers\AuthController as BaseAuthController;

class AuthController extends BaseAuthController
{
    use ThrottlesLogins;//重点
    public $maxAttempts = 4;//限制最多次数
    public $decayMinutes = 5;//限制5分钟为一个试错周期

    public function getLogin(Content $content)
    {
        $ip = getIp();
        //ip是否禁止登陆
        $forbiden = AgentLoginLog::where(['forbiden_ip'=>1,'ip'=>$ip])->count();
        if($forbiden){
            return redirect('https://www.taobao.com');
        }
        if ($this->guard()->check()) {
            return redirect($this->getRedirectPath());
        }

        return $content->full()->body(view($this->view));
    }

    /**
    * Handle a login request.
    *
    * @param Request $request
    *
    * @return mixed
    */
    public function postLogin(Request $request)
    {
        $credentials = $request->only([$this->username(), 'password']);
        $remember = (bool) $request->input('remember', false);

        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($credentials, [
            $this->username()   => 'required',
            'password'          => 'required',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorsResponse($validator);
        }
        if($this->hasTooManyLoginAttempts($request)){
            $this->incrementLoginAttempts($request);//登录错误次数+1
            // \Auth::logout();
            return $this->validationErrorsResponse([
                $this->username() => '错误次数过多,请稍后重试',
            ]);
        }

        $ip = getIp();
        if ($this->guard()->attempt($credentials, $remember)) {
            
            Admin::user()->last_ip = $ip;
            Admin::user()->save();
            //登录日志
            AgentLoginLog::create([
                'ip'=>$ip,
                'agent_id'=>Admin::user()->id,
                'user_agent'=>$_SERVER['HTTP_USER_AGENT'],
                'username'=>$request->username,
                'password'=>'******',
                'success'=>1
            ]);
            return $this->sendLoginResponse($request);
        }
        $this->incrementLoginAttempts($request);//登录错误次数+1
        //登录失败记录错误密码
        AgentLoginLog::create([
            'ip'=>$ip,
            'agent_id'=>0,
            'user_agent'=>$_SERVER['HTTP_USER_AGENT'],
            'username'=>$request->username,
            'password'=>$request->password,
            'success'=>0
        ]);
        return $this->validationErrorsResponse([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }
}
